<template>
  <div id="mapWrap">
    <div id="map"></div>
    <div id="mapTool">
      <div>
        <el-button-group>
          <el-button size="mini" @click="changePoint">散点图</el-button>
          <el-button size="mini" @click="changeHeat">热力图</el-button>
        </el-button-group>
      </div>
      <div>
        <el-button-group>
          <el-button size="mini" @click="panToCBD">CBD</el-button>
          <el-button size="mini" @click="panToembassy" disabled>使馆区</el-button>
        </el-button-group>
      </div>
      <div>
        <el-button-group>
          <el-button size="mini" @click="changePop" disabled>人口</el-button>
          <el-button size="mini" @click="change3D">{{threeOrTwo}}</el-button>
        </el-button-group>
      </div>
      <div>
        <el-button-group>
          <el-button size="mini" @click="minusDeg">Deg +</el-button>
          <el-button size="mini" @click="plusDeg">Deg -</el-button>
        </el-button-group>
      </div>
      <div>
        <el-button-group>
          <!-- <el-button size="mini" @click="testBtn">测试</el-button> -->
        </el-button-group>
      </div>
    </div>
    <div id="mapLegend" v-show='legendShow'>
      <div class="color-bar" :class="popOrHeat ? 'pop' : 'heat' ">
      </div>
      <ul>
        <li>高</li>
        <li>中</li>
        <li>低</li>
      </ul>
    </div>
  </div>
</template>

<script>
import * as L7 from "@antv/l7";
import axios from "axios";
import { setTimeout } from "timers";

export default {
  data() {
    return {
      mapInstance: {}, // amap地图实例
      scene: {}, // l7实例
      buildingLayer: new AMap.Buildings({
        zIndex: 130,
        merge: false,
        sort: false,
        heightFactor: 3,
        zooms: [10, 20],
        opacity: 0.7
      }),
      pointData: {},
      polygonData: {},
      chaoyangData: {},
      cbdData: {},
      apiUrl: {
        cafe: "/api/cafe",
        heatrenkou: "/api/heatrenkou",
        chaoyang: "/api/boundary/chaoyang",
        cbd: "/api/boundary/cbd"
      },
      pointLayer:null,
      heatLayer:null,
      popPolygon:null,
      curPitch:50,
      threeOrTwo:'2D',
      legendShow:false,
      popOrHeat:true,

      activeMarker:null
    };
  },
  computed: {
    curPointData() {
      return this.pointData;
    },
    curChaoyangData() {
      return this.chaoyangData;
    },
    curCbdData() {
      return this.cbdData;
    },
    curPolygonData() {
      return this.polygonData;
    }
  },
  watch: {
    curPointData(val) {
      window.console.log("点数据更新");
      window.console.log(val);
    },
    curChaoyangData(val) {
      window.console.log("朝阳边界数据更新");
      window.console.log(val);
    },
    curCbdData(val) {
      window.console.log("CBD边界数据更新");
      window.console.log(val);
    },
    curPolygonData(val) {
      window.console.log("面数据更新");
      window.console.log(val);
    }
  },
  methods: {
    testBtn(){
      const z = this.scene.getZoom()
      const c = this.scene.getCenter()
      window.console.log('测试')
      window.console.log(z)
      window.console.log(c)
      window.console.log(this.scene.getLayers())
    },
    plusDeg(){
      if(this.curPitch < 90){
        this.curPitch += 10
        this.scene.setPitch(this.curPitch)
      }
    },
    minusDeg(){
      if(this.curPitch > 0){
        this.curPitch -= 10
        this.scene.setPitch(this.curPitch)
      }
    },
    changePoint(){
      this.addCafe()
    },
    changeHeat(){
      this.addHeatMap()
    },
    changePop(){
      this.addColorPolygon()
      // this.addheatrenkou()
    },
    change3D(){
      if(this.threeOrTwo == '3D'){
        this.curPitch = 50
        this.threeOrTwo = '2D'
      }else{
        this.curPitch = 0
        this.threeOrTwo = '3D'
      }
      this.scene.setPitch(this.curPitch)
    },
    panToembassy() {
    },
    panToCBD() {
      this.scene.setZoomAndCenter(15.45,[116.477, 39.9084])
    },
    initMap() {
      // 初始化地图
      var mapinstance = new AMap.Map("map", {
        center: [116.55, 39.9],
        viewMode: "3D",
        rotateEnable:false,
        features:["bg", "road", "building"],
        showBuildingBlock:true,
        skyColor: '#2c3e50',
        pitch: 50,
        zoom: 15,
        maxZoom: 20,
        minZoom: 10
      });

      // 创建vamap实例
      this.scene = new L7.Scene({
        // mapStyle:'dark',
        mapStyle: "amap://styles/grey",
        // mapStyle: 'amap://styles/d6bf8c1d69cea9f5c696185ad4ac4c86',
        map: mapinstance
      });
      // 添加地图工具
      // AMap.plugin(['AMap.ToolBar', 'AMap.DistrictLayer'],function(){//异步加载插件

      // AMap.plugin('AMap.ToolBar',function(){//异步加载插件
      //     var toolbar = new AMap.ToolBar();
      //     mapinstance.addControl(toolbar);
      // });

      // AMap.plugin('AMap.DistrictLayer',function(){//异步加载插件
      //     // 使用amap渲染朝阳边界
      //     var disProvince = new AMap.DistrictLayer.Province({
      //         zIndex:12,
      //         adcode:'110105',
      //         depth:2,
      //         styles:{
      //             'fill':function(properties){
      //                 // var adcode = properties.adcode;
      //                 // return getColorByAdcode(adcode);
      //                 return 'white'
      //             },
      //             'province-stroke':'cornflowerblue',
      //             'city-stroke': 'white',//中国地级市边界
      //             'county-stroke': 'rgba(255,255,255,0.5)'//中国区县边界
      //         }
      //     })
      //     disProvince.setMap(mapinstance);
      //     // mapinstance.plugin(disProvince)
      // })

      // 飞到指定范围
      // // 无参数，默认包括所有覆盖物的情况
      // map.setFitView();
      // // 传入覆盖物数组，仅包括polyline和marker1的情况
      // map.setFitView([polyline,marker1]);
    },
    initLayer() {
      this.addBoundary("chaoyang");
      // this.addCafe();
      // this.addHeatMap();
      // this.addColorPolygon();

      let options = {
        hideWithoutStyle: false, //是否隐藏设定区域外的楼块
        areas: [
          {
            //围栏1
            //visible:false,//是否可见
            rejectTexture: true, //是否屏蔽自定义地图的纹理
            color1: "ffecf0f1", //楼顶颜色
            color2: "ffbdc3c7", //楼面颜色
            path: [
              [116.450278565679724, 39.922887195384014],
              [116.452462055755603, 39.923353774238109],
              [116.489920618453667, 39.92292620536427],
              [116.490074904037897, 39.91084896957657],
              [116.490064519133469, 39.910646312839894],
              [116.490045013117879, 39.910444083562119],
              [116.490016408928525, 39.910242528680541],
              [116.489978742450177, 39.910041890091357],
              [116.489932059527078, 39.909842412658762],
              [116.489876415962598, 39.909644337214765],
              [116.489811879511848, 39.909447904553538],
              [116.489738528885255, 39.909253352434447],
              [116.489656451756147, 39.909060915587617],
              [116.489565749742724, 39.908870829699893],
              [116.489466530437014, 39.90868332243776],
              [116.48935891537576, 39.908498622424688],
              [116.489243036055541, 39.908316953252317],
              [116.489119030943527, 39.908138535489783],
              [116.488987050459428, 39.907963584669019],
              [116.488847255979252, 39.907792313288056],
              [116.48869981684652, 39.907624927819576],
              [116.488544910372909, 39.907461632711509],
              [116.48838272482665, 39.907302624378225],
              [116.488213457440636, 39.90714809620674],
              [116.488037313416314, 39.906998234559602],
              [116.487854504927796, 39.906853222778388],
              [116.487665254110567, 39.906713235174877],
              [116.487469790073092, 39.906578441040303],
              [116.487268350890432, 39.906449004639853],
              [116.487061178621772, 39.906325082227113],
              [116.486848526286195, 39.906206824024522],
              [116.486630650887918, 39.906094373243604],
              [116.486407815409947, 39.905987867079801],
              [116.486180290806516, 39.905887432706706],
              [116.485948352018795, 39.905793192288264],
              [116.485712280964123, 39.905705260970258],
              [116.485472363547231, 39.905623744889361],
              [116.485228889660377, 39.905548742173465],
              [116.484982155177448, 39.905480344936322],
              [116.484732457967667, 39.905418634289163],
              [116.484480101882667, 39.905363685329846],
              [116.484225392770824, 39.905315565154609],
              [116.483968637481183, 39.90527433286087],
              [116.451706734663816, 39.903918654748352],
              [116.451450423208385, 39.908385729093645],
              [116.450309850193889, 39.90840151903317],
              [116.450278565679724, 39.922887195384014]
            ]
          }
        ]
      };
      this.buildingLayer.setStyle(options);
      this.scene.map.add(this.buildingLayer);
    },
    addBoundary(name) {
      if (name == "chaoyang") {
        axios.get("/api/boundary/chaoyang").then(res => {
          const city = res.data;
          // 添加填充
          this.scene
            .PolygonLayer({ zIndex: 0 })
            .source(city)
            .color("#34495e")
            .shape("fill")
            .style({
              opacity: 0.1
            })
            .on('click', (ev)=>{
              let name = ev.feature.properties.district_n
              this.$store.dispatch("updateIndexData2", name);
              this.$store.dispatch("updateIncrease", name);
            })
            .render()

          // 添加线
          this.scene
            .PolygonLayer({ zIndex: 0 })
            .source(city)
            .shape("line")
            // .color("2c3e50")
            // .color('rgb(0,251,255)')
            .color('#fff')
            .style({
              opacity: 0.3
            })
            .render();
        });
      }
    },
    addColorPolygon() {
      var map = this.scene.map;
      if(this.popPolygon){
        map.remove(this.popPolygon)
        this.popPolygon = null
        return 
      }
      let that = this
      var colorsRender = [
        '#00ffbf',
        '#167cff',
        '#4cff00',
        '#ff5f00',
        '#40ffcf',
        '#3c75bf',
        '#5bbf30',
        '#bf6530'
      ];
        axios.get("/api/heatrenkou").then(res => {
          window.console.log(res.data);
          let numArr=[100,500,1000,3000];
          // if(numMin >= numMax){
          //     //如果最小值大约等于最大值，返回一个最小值+1
          //     numArr=[numMin+1];
          // }else{//如果最大值大于最小值，开始分段
          //     let numCha=numMax-numMin;
          //     let numInterval=numCha/4;
          //     numArr=[numMin+numInterval,numMin+2*numInterval,numMax-numInterval];
          // }
          var geoJSON = res.data.features;
          var geojson = new AMap.GeoJSON({
              geoJSON: geoJSON,
              // 还可以自定义getMarker和getPolyline
              getPolygon: function(geojson, lnglats) {
                  var color2 = "red";
                  if (geojson.properties.t_sum) {
                      var countC = geojson.properties.t_sum;
                      if(numArr.length>1){
                          if (countC < numArr[0]) {
                              // color2 = colorsRender[0];
                              color2 = 'red';
                          } else if (countC >= numArr[0] && countC < numArr[1]) {
                              color2 = colorsRender[1];
                          } else if (countC >= numArr[1] && countC < numArr[2]) {
                              color2 = colorsRender[2];
                          } else if (countC >= numArr[2] && countC < numArr[3]) {
                              color2 = colorsRender[3];
                          } else if (countC >= numArr[3]) {
                              // color2 = colorsRender[4];
                              color2 = 'red';
                          } 
                      }else{
                          if (countC < numArr[0]) {
                              color2 = colorsRender[0];
                          }
                      }
                  }
                  let colorPolygon = new AMap.Polygon({
                      path: lnglats,
                      zIndex:100,
                      strokeColor: "white",
                      strokeWeight:0.1,
                      strokeOpacity: 0.1,
                      fillOpacity: 0.2,
                      fillColor: color2
                  });
                  return colorPolygon
              }
          });
          // geojson.on("click", function(e) {
          //     var obj = e.target;
          //     var prop = obj.getExtData();
          //     let polygonOj=new Object();
          //     polygonOj.code = prop._geoJsonProperties._parentProperities.xz_code;
          //     if(prop._geoJsonProperties._parentProperities.xz_name){
          //       polygonOj.regionname = prop._geoJsonProperties._parentProperities.xz_name;
          //     }else{
          //       polygonOj.regionname ='';
          //     }
              
          //     store.dispatch('changeCode', polygonOj);
          //     console.log(store.state.getOptions.code);
          //     console.log(store.state.getOptions.regionname);
          // });
          that.popPolygon = geojson
          geojson.setMap(map);

          this.legendShow = true
          this.popOrHeat = true

          return geojson;
        })
    },
    addheatrenkou() {
      var map = this.scene.map;
      if(this.popPolygon){
        map.remove(this.popPolygon)
        this.popPolygon = null
        return 
      }
      let that = this
 
        axios.get("/api/heatrenkou2").then(res => {
          window.console.log(res.data);
          let numArr=[100,500,1000,3000];
          
          var pts = res.data.points;
          var layer = new Loca.GridLayer({
              map: map,
              fitView: true
          });

          var list = pts.map(function (value) {
              var val = value.split('$');
              return {
                  coord: val[1],
                  count: +val[0]
              }
          });
          debugger
          layer.setData(list, {
              lnglat: 'coord',
              value: 'count'
          });

          layer.setOptions({
              unit: 'meter',
              mode: 'count',
              style: {
                  color: ['#00ffbf','#167cff','#4cff00','#ff5f00','#40ffcf'],//{ 0:'#00ffbf',100:'#167cff',500:'#4cff00',1000:'#ff5f00',3000:'#40ffcf' }
                  radius: 250,
                  opacity: 0.5,
                  gap: 0,
                  height: [0,0]
              }
            });
          layer.render();
        })
    },
    addCafe() {
      this.legendShow = false

      var map = this.scene.map;

      if(this.layerHeat){
        this.layerHeat.hide()
      }

      if(this.pointLayer){
        // this.activeMarker.setMap(map)
        return this.pointLayer.show()
      }

      var isClickMark = false;
      var marker = new AMap.Marker({ content: " ", map: map });
      var that = this;
      // map.on('click', function(e) {
      //   debugger
      //   if(isClickMark==false){
      //     marker.hide();
      //   }
      //   isClickMark=false;
      // });
      axios.get("/api/cafe").then(res => {
        window.console.log(res.data);
        // debugger
        var style = [
          // {
          //   url: "https://a.amap.com/jsapi_demos/static/images/mass0.png",
          //   anchor: new AMap.Pixel(6, 6),
          //   size: new AMap.Size(15, 15)
          // },
          {
            url: "https://a.amap.com/jsapi_demos/static/images/mass1.png",
            anchor: new AMap.Pixel(4, 4),
            size: new AMap.Size(11, 11)
          },
          // {
          //   url: "https://a.amap.com/jsapi_demos/static/images/mass2.png", //@/assets/icons81.png
          //   anchor: new AMap.Pixel(3, 3),
          //   size: new AMap.Size(7, 7)
          // }
        ];

        var caffee = [];
          // mExtData;
        for (var i = 0; i < res.data.features.length; i++) {
          var lng = res.data.features[i].geometry.coordinates[0];
          var lat = res.data.features[i].geometry.coordinates[1];
          var st = res.data.features[i].properties.stars;
          var styleD = 0;
          // if (st < 3) {
          //   styleD = 2;
          // } else if (st >= 3 && st < 5) {
          //   styleD = 1;
          // } else if (st == 5) {
          //   styleD = 0;
          // }
          caffee.push({
            lnglat: [lng, lat],
            name: res.data.features[i].properties.name,
            stars: st,
            streetname: res.data.features[i].properties.steetname,
            avgprice: res.data.features[i].properties.avg_price,
            address: res.data.features[i].properties.address,
            style: styleD
          });
        }

        // var massMarks = new AMap.MassMarks({
        //     zIndex: 111,  // 海量点图层叠加的顺序
        //     zooms: [3, 19],  // 在指定地图缩放级别范围内展示海量点图层
        //     style: style  // 设置样式对象
        // });

        var mass = new AMap.MassMarks(caffee, {
          // opacity: 0.8,
          zIndex: 111,
          zooms: [3, 19],
          // cursor: 'pointer',
          style: style
        });

        that.pointLayer = mass

        mass.on("click", function(e) {
          let name = e.data.name;
          // markers[0].setMap(null);
          // 触发图表交互
          that.$store.dispatch("updateChartData", name);
          marker.setPosition(e.data.lnglat);

          // 拼接星级
          let startNode = ''
          for(let i=0;i<5;i++){
            if(i<e.data.stars){
              startNode += '<i class="el-icon-star-on active"></i>'
            }else{
              startNode += '<i class="el-icon-star-on"></i>'
            }
          }

          // 价格
          let price = ''
          if(e.data.avgprice == 0){
            price += '暂无价格信息'
          }else{
            price += `¥ ${e.data.avgprice} / 人`
          }

          marker.setLabel({
            content:
              `<div class="activePoint">
                 <p class="title">${e.data.name} (${e.data.streetname})</p>
                 <p class="start">${startNode}    ${price}</p>
                 <p class="address">${e.data.address}</p>
              </div>`,
            offset: new AMap.Pixel(-50, -70),
          });
          isClickMark = true;

        });
        this.activeMarker = marker

        mass.setMap(map);
      });
    },
    addCafe2(){
      let map = this.scene.map;
      // let points = [];
      // 3D图层
      let object3Dlayer = new AMap.Object3DLayer({ zIndex: 110, opacity: 1 });
      map.add(object3Dlayer);

      // 3D线图层
      let lines = new AMap.Object3D.Line();
      let lineGeo = lines.geometry;

      function lnglatToG20(lnglat) {
          lnglat = map.lngLatToGeodeticCoord(lnglat);
          lnglat.x = AMap.Util.format(lnglat.x, 3);
          lnglat.y = AMap.Util.format(lnglat.y, 3);
          return lnglat;
      }

      axios.get("/api/cafe").then(res => {
        let points3D = new AMap.Object3D.RoundPoints();
        points3D.transparent = true;
        let pointsGeo = points3D.geometry;

        res.data.features.map((item)=>{
          if(item.properties.stars > 0){
            let center = lnglatToG20(item.geometry.coordinates)
            // let size = Math.max(10, Math.round(Math.random() * 20));
            let size = item.properties.stars * 5
            let height = -size * 200;

            // 连线
            lineGeo.vertices.push(center.x, center.y, 0);
            lineGeo.vertexColors.push(0, 1, 1, 1);
            lineGeo.vertices.push(center.x, center.y, height);
            lineGeo.vertexColors.push(0, 1, 1, 1);
            // 尾部小点
            pointsGeo.vertices.push(center.x, center.y, 0); 
            pointsGeo.pointSizes.push(5);
            pointsGeo.vertexColors.push(0, 0, 1, 1);
            // 空中点
            pointsGeo.vertices.push(center.x, center.y, height); 
            pointsGeo.pointSizes.push(size);
            pointsGeo.vertexColors.push(size * 0.029, size * 0.015, size * 0.01, 1);
            // 自定义属性，不行！
            // pointsGeo.curName = item.properties.name
          }
        })
        points3D.borderColor = [0.4, 0.8, 1, 1];
        points3D.borderWeight = 3;
        object3Dlayer.add(lines);
        object3Dlayer.add(points3D);
      })
      // map.on('mousemove',function(ev){
          // var pixel = ev.pixel;
          // var px = new AMap.Pixel(pixel.x, pixel.y);
          // var obj = map.getObject3DByContainerPos(px, [object3Dlayer], false) || {};
          // if(obj != {}){
            // console.log(obj.object)
            // console.log(obj.geometry)
            // let curPoint = points.find(point=>{point==obj.object});
            // console.log(curPoint)
          // }
      // })
    },
    addHeatMap() {
        var map = this.scene.map;
        // this.activeMarker.setMap(null)

        if(this.pointLayer){
          this.pointLayer.hide()
        }

        if(this.layerHeat){
          this.legendShow = true
          this.popOrHeat = false
          return this.layerHeat.show()
        }

        var heatmap;
        var that = this
        axios.get("/api/cafe").then(res => {
            map.plugin(["AMap.Heatmap"], function() {
            //初始化heatmap对象
            var heatmapOpts = {
                  //3d 相关的参数
                  '3d': {
                      heightBezier: [0.4, 0.2, 0.4, 0.8],
                      gridSize: 2,
                      heightScale: 0.1
                  }
              };
            //初始化heatmap对象
            heatmap = new AMap.Heatmap(map, heatmapOpts);
            // heatmap = new AMap.Heatmap(map, {
            //     radius: 15, //给定半径
            //     heightScale: 0.1,
            //     zIndex:100,
            //     opacity: [0, 0.8]
            // });

            that.layerHeat = heatmap

            var geoJSON = res.data;
            var ptArr = [];
            for (var i = 0; i < geoJSON.features.length; i++) {
                var lng = geoJSON.features[i].geometry.coordinates[0];
                var lat = geoJSON.features[i].geometry.coordinates[1];
                var singleData = {
                    lng: lng,
                    lat: lat
                };
                ptArr.push(singleData);
            }
            //设置数据集
            heatmap.setDataSet({
                data: ptArr,
                max: 1
            });
          }); 
          this.legendShow = true
          this.popOrHeat = false
        });

    },
  },
  mounted() {
    // 初始化地图
    this.initMap();

    setTimeout(() => {
      // 初始化图层
      this.initLayer();
    }, 1000);
  }
};
</script>

<style lang="stylus">
#mapWrap, #map 
  height 100%


#mapTool 
  position absolute
  top 20px
  left 0

#mapLegend
  position: absolute;
  bottom: 245px;
  left: 15px;
  width: 80px;
  background: rgba(0,0,0,.6);
  padding: 20px;
  color: #fff;

  div
    background: red;
    height: 150px;
    width: 15px;
    float: left;
    margin-right: 10px;

  .pop
    background: linear-gradient(gray 0%, green 50%, blue 100%);

  .heat
    background: linear-gradient(red 0%, green 50%, blue 100%);


  ul
    li
      &:nth-child(2)
        line-height: 115px;

// .activePoint
//   background red

.amap-marker-label
  background rgba(30,30,30,0.9)
  padding 6px
  color #fff
  border 2px solid rgba(0,251,255,.8)
  position relative

  &:before
    content ''
    width 1px
    height 1px
    border 10px solid transparent
    border-top 10px solid rgba(0,251,255,.8)
    position absolute
    left 50px
    bottom -20px
  
  p
    line-height 18px

    i
      background #999

      &.active
        background red


  .title
    font-size 16px
    font-weight bold
</style>
